<script setup>
import { ref, reactive, onMounted, computed, toRaw } from "vue";
import { useI18n } from "vue-i18n";
import { useConfigStore } from "@/store/modules/config";
import AppHeader from "@/components/app_header.vue";
import { useRouter } from "vue-router";
// import { userOrderApi } from "@/api/public";
import { getTime } from "@/utils";
import { showSuccessToast, showToast } from "vant";
import { isMobileDevice } from "@/utils/base_index";
const router = useRouter();

const ToBlack = () => {
  router.push("home");
};
const useConfig = useConfigStore();

const { locale, t } = useI18n();
const isShow = ref(false);
const loading = ref(false);
const finished = ref(false);
const list = reactive([]);
const tabs = reactive([t("exchange.buyIn"), t("exchange.sellOut")]);

const onLoad = () => {
  setTimeout(() => {
    for (let i = 0; i < 4; i++) {
      list.push(list.length + 1);
    }
    // 加载状态结束
    loading.value = false;

    // 数据全部加载完成
    if (list.length >= 20) {
      finished.value = true;
    }
  }, 500);
};

// 切换中文
function changeZh() {
  locale.value = "zh";
  localStorage.setItem("lang", "ch");
}
// 切换英文
function changeLang() {
  const lang = localStorage.getItem("lang");
  const newVal = lang && lang === "ch" ? "en" : "ch";
  locale.value = newVal;
  localStorage.setItem("lang", newVal);
}

// 切换英文
function showDialog() {
  isShow.value = true;
}

/// ======================bigv

const active = ref(0);

const orderList = ref([]);
const orderCount = ref(0);
const size = 10;
const page = ref(1);

// const setPage = v => {
//   page.value = v;
//   loadData();
// };

// 加载更多
const loadMore = () => {
  if (orderCount.value === 0 || orderList.value.length >= orderCount.value)
    return;
  page.value++;
  // page.value = v;
  loadData();
  console.log("加载更多");
};

const resetLoad = () => {
  page.value = 1;
  orderList.value = [];
  orderCount.value = 0;
  loadData();
};

const loadData = async () => {
  if (orderCount.value === 0) {
    const count = await useConfig.getMasterContract.methods
      .getTradeHistoryCount(useConfig.account)
      .call();
    const _count = useConfig.web3.utils.toNumber(count);
    console.log("_count", _count);
    orderCount.value = _count;
  }
  // 总条数 = 0 || 数据条数 >= 总条数 : 停止获取数据
  if (orderCount.value === 0 || orderList.value.length >= orderCount.value)
    return;

  let startIndex = orderCount.value - page.value * size;
  startIndex = startIndex < 0 ? 0 : startIndex;

  let remainingItems = orderCount.value - (page.value - 1) * size;
  let count = remainingItems < size ? remainingItems : size;

  const res = await useConfig.masterContract.methods
    .getTradeHistorys(useConfig.account, startIndex, count)
    .call();
  const _res = res.map(v => {
    return {
      sellAddress: v.sellAddress,
      creationTime: useConfig.web3.utils.toNumber(v.creationTime),
      price: useConfig.web3.utils.fromWei(v.price, "ether"),
      inCptAmount: useConfig.web3.utils.fromWei(v.inCptAmount, "ether"),
      outCptAmount: useConfig.web3.utils.fromWei(v.outCptAmount, "ether"),
      outUsdtAmount: useConfig.web3.utils.fromWei(v.outUsdtAmount, "ether"),
      status: useConfig.web3.utils.toNumber(v.status),
      buyAddress: v.buyAdresss,
      buyCptAmount: useConfig.web3.utils.fromWei(v.buyCptAmount, "ether"),
      buyUsdtAmount: useConfig.web3.utils.fromWei(v.buyUsdtAmount, "ether"),
      updateTime: useConfig.web3.utils.toNumber(v.updateTime)
    };
  });
  console.log(res);
  orderList.value = orderList.value.concat(_res.reverse());
};

const pendingOrderList = ref([]);
const loadPendingOrderData = async () => {
  const res = await useConfig.masterContract.methods
    .getTradeCurrent(useConfig.account)
    .call();
  const { sellAddress } = res;
  if (
    sellAddress.toLocaleLowerCase() === useConfig.account.toLocaleLowerCase()
  ) {
    const _res = {
      sellAddress: res.sellAddress,
      creationTime: useConfig.web3.utils.toNumber(res.creationTime),
      price: useConfig.web3.utils.fromWei(res.price, "ether"),
      inCptAmount: useConfig.web3.utils.fromWei(res.inCptAmount, "ether"),
      outCptAmount: useConfig.web3.utils.fromWei(res.outCptAmount, "ether"),
      outUsdtAmount: useConfig.web3.utils.fromWei(res.outUsdtAmount, "ether"),
      status: useConfig.web3.utils.toNumber(res.status),
      buyAddress: res.buyAdresss,
      buyCptAmount: useConfig.web3.utils.fromWei(res.buyCptAmount, "ether"),
      buyUsdtAmount: useConfig.web3.utils.fromWei(res.buyUsdtAmount, "ether"),
      updateTime: useConfig.web3.utils.toNumber(res.updateTime)
    };
    pendingOrderList.value = [_res];
  } else {
    pendingOrderList.value = [];
  }
  console.log("实时挂单", res);
};

// 买单
const buyOrderList = computed(() => {
  const _orderList = toRaw(orderList.value);
  if (_orderList.length == 0) {
    return [];
  }
  return _orderList.filter(
    v =>
      v.buyAddress.toLocaleLowerCase() === useConfig.account.toLocaleLowerCase()
  );
});

// 卖单
const sellOrderList = computed(() => {
  const _orderList = toRaw(orderList.value);
  if (_orderList.length == 0) {
    return [];
  }
  return _orderList.filter(
    v =>
      v.sellAddress.toLocaleLowerCase() ===
      useConfig.account.toLocaleLowerCase()
  );
});

// 撤单
const cancelFn = async () => {
  const data = useConfig.masterContract.methods.cancel().encodeABI();
  const params = {
    to: useConfig.masterContractAddress,
    from: useConfig.getAccount,
    value: useConfig.getWbe3.utils.toHex(0),
    data
  };
  try {
    const gasLimit = await useConfig.getWbe3.eth.estimateGas(params);
    params.gas = useConfig.getWbe3.utils.toHex(gasLimit);
  } catch (error) {
    // params.gas = useConfig.getWbe3.utils.toHex(200000);
  }
  useConfig.getWbe3.eth
    .sendTransaction(params)
    .on("transactionHash", function (hash) {
      console.log("hash", hash);
      showSuccessToast(t("bigv.success"));
    })
    .on("receipt", receipt => {
      console.log("receipt", receipt);
      loadPendingOrderData();
      resetLoad();
    })
    .catch(error => {
      showToast(error.data.message);
      console.error("error:", error.data);
    });
};

const statusStr = v => {
  switch (v) {
    case 1:
      return "未成交";
    case 2:
      return "已成交";
    case 3:
      return "已撤销";

    default:
      return "--";
  }
};

onMounted(() => {
  loadData();
  loadPendingOrderData();
});
</script>

<template>
  <div class="home div-container">
    <!-- header--start-->
    <div class="div-header">
      <div class="div-left" @click.stop="ToBlack">
        <img src="@/assets/icon-black.png" alt="" />
      </div>
      <span class="title">
        <img src="@/assets/icon-logo.png" width="40" alt="" />
      </span>
      <div class="div-right">...</div>
    </div>
    <AppHeader />

    <div class="div-record">
      <div class="div-record-title">{{ $t("exchange.record") }}</div>
      <van-tabs v-model:active="active">
        <van-tab :title="$t('exchange.buyIn')">
          <div v-if="buyOrderList.length === 0" class="div-list-empty">
            <img
              src="./../../assets/icon-revenue-empty.png"
              width="150"
              alt=""
            />
            <p>{{ $t("transaction.tableEmpty") }}</p>
          </div>

          <div v-for="(v, i) in buyOrderList" :key="i" class="div-list-item">
            <div class="div-top">
              <span class="div-status div-success">{{
                $t("transaction.transacted")
              }}</span>
            </div>

            <p class="div-price">{{ $t("transaction.price") }}(USDT)</p>
            <p class="div-amount">{{ v.price }}</p>

            <p class="pay-detail">
              <span class="sub-desc">{{ $t("transaction.payAmount") }}：</span
              >{{ v.buyUsdtAmount }}
              USDT
            </p>
            <p class="pay-detail">
              <span class="sub-desc">{{ $t("transaction.buyQuantity") }}：</span
              >{{ v.buyCptAmount }}
              {{ useConfig.name }}
            </p>
            <p class="pay-detail">
              <span class="sub-desc"
                >{{ $t("transaction.exchangeTime") }}：</span
              >{{ getTime(v.updateTime) }}
            </p>
          </div>
        </van-tab>
        <van-tab :title="t('exchange.sellOut')">
          <div
            v-if="pendingOrderList.length === 0 && sellOrderList.length === 0"
            class="div-list-empty"
          >
            <img
              src="./../../assets/icon-revenue-empty.png"
              width="150"
              alt=""
            />
            <p>{{ $t("transaction.tableEmpty") }}</p>
          </div>

          <div
            v-for="(v, i) in pendingOrderList"
            :key="i"
            class="div-list-item"
          >
            <div class="div-top">
              <span
                class="div-status"
                :class="{
                  'div-success': v.status === 2,
                  'div-cancel': v.status === 3
                }"
                >{{ statusStr(v.status) }}</span
              >
            </div>
            <p class="div-price">{{ $t("transaction.price") }}(USDT)</p>
            <p class="div-amount">{{ v.price }}</p>
            <p class="pay-detail">
              <span class="sub-desc"
                >{{ $t("transaction.salesQuantity") }}：</span
              >{{ v.inCptAmount }}
              {{ useConfig.name }}
            </p>
            <p class="pay-detail">
              <span class="sub-desc"
                >{{ $t("transaction.transactionQuantity") }}：</span
              >{{ parseFloat(v.outCptAmount) }}
              {{ useConfig.name }}
            </p>
            <p class="pay-detail">
              <span class="sub-desc"
                >{{ $t("transaction.exchangeTime") }}：</span
              >{{ getTime(v.creationTime) }}
            </p>
            <div class="div-btn" @click="cancelFn">
              {{ $t("transaction.cancel") }}
            </div>
          </div>

          <div v-for="(v, i) in sellOrderList" :key="i" class="div-list-item">
            <div class="div-top">
              <span
                class="div-status"
                :class="{
                  'div-success': v.status === 2,
                  'div-cancel': v.status === 3
                }"
                >{{ statusStr(v.status) }}</span
              >
            </div>

            <p class="div-price">{{ $t("transaction.price") }}(USDT)</p>
            <p class="div-amount">{{ v.price }}</p>
            <p class="pay-detail">
              <span class="sub-desc"
                >{{ $t("transaction.salesQuantity") }}：</span
              >{{ v.inCptAmount }}
              {{ useConfig.name }}
            </p>
            <p class="pay-detail">
              <span class="sub-desc"
                >{{ $t("transaction.transactionQuantity") }}：</span
              >{{ v.outCptAmount }}
              {{ useConfig.name }}
            </p>
            <p class="pay-detail">
              <span class="sub-desc"
                >{{ $t("transaction.exchangeTime") }}：</span
              >
              {{ getTime(v.creationTime) }}
            </p>
          </div>
        </van-tab>
      </van-tabs>
      <div v-if="orderList.length < orderCount" class="div-load-more">
        <van-divider :margin="12" @click.stop="loadMore">
          {{ $t("pledge.loadMore") }}
        </van-divider>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
@import "./../../styles/mixin.less";
p {
  margin: 0px;
}
.home {
  font-size: 14px;
  color: #ffffff;
  padding-bottom: 20px;
}
.div-wallet {
  height: 44px;
  padding: 0 14px;
  display: flex;
  font-size: 14px;
  justify-content: space-between;
  & > div {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .wallet {
    padding-left: 10px;
    padding-right: 10px;
    border-radius: 20px;
    border: 1px solid #9cb3bf;
  }
}
.div-record {
  padding: 20px 14px;
  position: relative;
  &-title {
    font-weight: 500;
    font-size: 23px;
    color: #e5f0f4;
    line-height: 40px;
    text-indent: 14px;
    position: relative;
    &:before {
      display: block;
      content: "";
      width: 5px;
      height: 23px;
      position: absolute;
      left: 0px;
      top: 8px;
      background-color: #ff6393;
      border-radius: 5px;
    }
  }
  :deep(.van-tabs__wrap) {
    margin-top: 10px;
    margin-bottom: 10px;
  }
  :deep(.van-tabs__nav) {
    font-size: 14px;
    color: #606374;
    background-color: #171826;
  }
  :deep(.van-tab--active) {
    font-weight: normal;
    color: #fff;
    background-color: #0066ff;
  }
  :deep(.van-tabs__line) {
    display: none;
  }
  :deep(.van-tab) {
    flex: none;
    width: 65px;
    height: 32px;
  }
  .div-list-empty {
    padding: 40px 10px;
    background: #27283e;
    border-radius: 20px;
    border: 1px solid #62737f;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    p {
      font-size: 16px;
      color: #606374;
    }
  }
  .div-list {
    &-item {
      margin-bottom: 18px;
      padding: 20px 22px;
      background: #27283e;
      border-radius: 20px;
      border: 1px solid #62737f;
      position: relative;
      .div-top {
        font-size: 16px;
        font-weight: bold;
        display: flex;
        justify-content: space-between;
        .div-status {
          color: #ffffff;
        }
        .div-success {
          color: #47ddc2;
        }
        .div-cancel {
          color: #ff6393;
        }
      }
      .div-price {
        padding-bottom: 10px;
        margin-top: 25px;
        font-size: 13px;
        color: #e5f0f4;
      }
      .div-amount {
        font-weight: 500;
        font-size: 21px;
        color: #e5f0f4;
        line-height: 30px;
        padding-bottom: 14px;
      }
      .pay-detail {
        font-size: 13px;
        color: #fff;
        line-height: 24px;
        .sub-desc {
          color: #62737f;
        }
      }
      .div-btn {
        position: absolute;
        right: 22px;
        bottom: 22px;
        padding: 10px 26px;
        border-radius: 8px;
        background: linear-gradient(57deg, #47ddc2 0%, #c1ffc8 100%);
      }
    }
  }
}
</style>
